package org.example.leetCode;

import org.example.entity.ListNode;

/**
 * 19. 删除链表的倒数第 N 个结点
 * 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。
 */
public class Code19 {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        //虚拟头节点
        ListNode result = new ListNode(0, head);
        //初始化双指针
        ListNode first = result;
        ListNode second = result;
        //双指针保持间距n
        for (int i = 0; i <= n; i++) {
            first = first.next;
        }
        //同时移动双指针，直到first为空
        while (first != null) {
            first = first.next;
            second = second.next;
        }
        second.next = second.next.next;
        return result.next;

    }
    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        Code19 code19 = new Code19();
        ListNode result = code19.removeNthFromEnd(node1, 2);

    }



}
